﻿using System;
using msilgc.cbuilder.CSyntaxTree;
using msilgc.cbuilder.MSILSyntaxTree;
using msilgc.CSyntaxTree;

namespace msilgc.cbuilder.CBuilder {
    internal class LoadElementAddressAsTranslator : ITranslator {
        private readonly VariableFactory _varFactory;

        public LoadElementAddressAsTranslator(VariableFactory varFactory) {
            _varFactory = varFactory;
        }

        public ICStatement TranslateAndAdd(CMethodBody methodBody, CBasicBlock currentBlock, BasicBlock block, Instruction instruction) {
            IVariable index = EvaluationStackHelper.PopVariableOffEvaluationStack(currentBlock);
            IVariable array = EvaluationStackHelper.PopVariableOffEvaluationStack(currentBlock);
            if(instruction.InlineType == null)
            {
                throw new Exception("expected instruction [" + instruction + "] to have an inline type");
            }
            IVariable target = _varFactory.CreateNext(instruction.InlineType);
            target.IsPointer = true;
            AssignToLocalVariableFromArray arrayLoadStm = new AssignToLocalVariableFromArray(target, array, index){AddressOf = true};
            currentBlock.Statements.Add(arrayLoadStm);
            return arrayLoadStm;
        }
    }
}
